from httpx import AsyncClient
from src.utils import get_config
from .typings import (
    UserExam,
    ExamDetail,
)
from fastapi.logger import logger


base_url = get_config().answer_url
user_exams_url = "/api/answer/userExams/{}"
user_exams_list_url = "api/answer/userExams/list"


class ExamResult:
    def __init__(self, user_exam_id: str, headers: dict):
        self.user_exam_id = user_exam_id
        self.headers = {
            "authorization": headers.get("authorization", ""),
            "clientid": headers.get("clientid", ""),
            "user-agent": headers.get("user-agent", ""),
        }
        self.client = AsyncClient(base_url=base_url, headers=self.headers)

    def clean_exam_data(self, data: dict) -> dict:
        """清理考试数据，处理 None 值"""
        if data and "questions" in data:
            for question in data["questions"]:
                if "options" in question:
                    for i, option in enumerate(question["options"]):
                        # 处理 optionOrder 为 None 的情况
                        if option.get("optionOrder") is None:
                            option["optionOrder"] = i + 1  # 使用索引+1作为默认值
        return data

    async def get_exam_list(self):
        response = await self.client.get(user_exams_list_url)
        data = response.json().get("data", [])
        return [UserExam(**item) for item in data]

    async def get_exam_result(self, userExamId: str | int | None = None) -> ExamDetail:
        userExamId = userExamId or self.user_exam_id
        if not userExamId:
            raise ValueError("userExamId is required")
        response = await self.client.get(f"/api/answer/userExams/{userExamId}")
        raw_data = response.json()
        data = raw_data.get("data", None)
        # 如果远端返回 data 为 None，记录并抛出可读的错误，避免把 None 传给 Pydantic
        if data is None:
            # 记录完整响应，便于排查
            logger.error("Received empty data from answer service: %s", raw_data)
            raise ValueError(f"Remote answer service returned no data for userExamId={userExamId}")

        # 清理数据
        logger.info("Received exam data: %s", data)
        cleaned_data = self.clean_exam_data(data)

        # 验证并返回
        try:
            return ExamDetail.model_validate(cleaned_data)
        finally:
            # 关闭 client 连接池
            await self.client.aclose()
